package com.unlcn.ils.kas.service.map.BaiDuMap.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.unlcn.ils.kas.dao.model.order.BaiduException;
import com.unlcn.ils.kas.service.map.BaiDuMap.config.BaiDuMapCoreConfig;
import com.unlcn.ils.kas.service.map.BaiDuMap.config.BaiDuMapRouteConfig;
import com.unlcn.ils.kas.service.order.IBaiduExceptionService;
import com.unlcn.ils.kas.service.util.BaseException;
import com.unlcn.ils.kas.service.util.HttpClientUtil;
import com.unlcn.ils.kas.service.util.enums.BaiDuMapStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class BaiDuMapRouteUtil {

    private static final Logger logger = LoggerFactory.getLogger(BaiDuMapRouteUtil.class);


    private static int socketTimeout = 10000;

    //静态注入的方式
    private static BaiDuMapCoreConfig baiDuMapCoreConfig;

    private static BaiDuMapRouteConfig baiDuMapRouteConfig;


    @Autowired
    public void setBaiDuMapCoreConfig(BaiDuMapCoreConfig baiDuMapCoreConfig) {
        BaiDuMapRouteUtil.baiDuMapCoreConfig = baiDuMapCoreConfig;
    }

    @Autowired
    public void setBaiDuMapGeoConfig(BaiDuMapRouteConfig baiDuMapRouteConfig) {
        BaiDuMapRouteUtil.baiDuMapRouteConfig = baiDuMapRouteConfig;
    }


    public static IBaiduExceptionService iBaiduExceptionService;
    @Autowired
    public void setiBaiduExceptionService(IBaiduExceptionService iBaiduExceptionService){
        BaiDuMapRouteUtil.iBaiduExceptionService=iBaiduExceptionService;
    }
    /**
     * 获取两地之间默认驾车导航距离
     *
     * @param origins
     * @param destinations
     * @param tactics      只对驾车算路(driving)生效。 
     *                     可选值：10 不走高速；11 最短时间；12 最短路径；13 最短 距离(不考虑路况); 
     *                     其中10-12 都考虑实时路况，若希望计算最可靠的最短路线距离，建议使用不考虑实时路况的默认值13。
     * @return 单位米
     * @throws BaseException
     * Modify:wanlei 20181205 添加
     */
    public static double getDistance(String origins, String destinations, String tactics) throws BaseException {
        double distance = 0;
        JSONObject jsonObject = null;
        try {
            Map<String, Double> mapOrgrin = BaiDuMapGeocodeUtil.addressToGPS(origins);
            Map<String, Double> mapDestinations = BaiDuMapGeocodeUtil.addressToGPS(destinations);
            distance = getDistance(mapOrgrin, mapDestinations, tactics);
        } catch (Exception ex) {
            logger.error("getDistance URL error: {}", ex);
            BaiduException baiduException = new BaiduException();
            baiduException.setAddress(origins+destinations);
            baiduException.setGmtCreate(new Date());
            baiduException.setExceptionMsg(ex.getMessage());
            iBaiduExceptionService.insert(baiduException);

        }
        return distance;
    }

    /**
     * 获取两地之间默认驾车导航距离
     *
     * @param mapOrgrin       起始点坐标的map lat 纬度 lng 经度
     * @param mapDestinations 终点坐标的map lat 纬度 lng 经度
     * @param tactics         只对驾车算路(driving)生效。 
     *                        可选值：10 不走高速；11 最短时间；12 最短路径；13 最短 距离(不考虑路况); 
     *                        其中10-12 都考虑实时路况，若希望计算最可靠的最短路线距离，建议使用不考虑实时路况的默认值13。
     * @return
     * @throws BaseException
     */
    public static double getDistance(Map<String, Double> mapOrgrin, Map<String, Double> mapDestinations, String tactics) throws BaseException {
        float distance = 0;
        JSONObject jsonObject = null;

        try {
            String originsCode = mapOrgrin.get("lat") + "," + mapOrgrin.get("lng");
            String destinationCode = mapDestinations.get("lat") + "," + mapDestinations.get("lng");
            String url = String.format(baiDuMapRouteConfig.getDriveRouterUrl(), originsCode, destinationCode, tactics, baiDuMapCoreConfig.getApiKey());
            try {
                String strReturn = HttpClientUtil.get(url, null, socketTimeout);
                jsonObject = JSON.parseObject(strReturn);
                int status = jsonObject.getInteger("status");
                String msg = BaiDuMapStatusEnum.getTest(status);
                if (status == 0) {
                    distance = jsonObject.getJSONArray("result").getJSONObject(0).getJSONObject("distance").getFloat("value");
                } else {
                    throw new BaseException(msg);
                }
            } catch (Exception e) {
                logger.error("getDistance URL error: {}", e);
                logger.error("URL error: {}", e);
                BaiduException baiduException = new BaiduException();
                baiduException.setGmtCreate(new Date());
                baiduException.setExceptionMsg(e.getMessage());
                baiduException.setOriginLatitude(String.valueOf(mapOrgrin.get("lat")));
                baiduException.setOriginLongitude(String.valueOf(mapOrgrin.get("lng")));
                baiduException.setDestinationLatitude(String.valueOf(mapDestinations.get("lat")));
                baiduException.setDestinationLongitude(String.valueOf(mapDestinations.get("lng")));
                iBaiduExceptionService.insert(baiduException);

            }
        } catch (Exception ex) {
            logger.error("getDistance URL error: {}", ex);
            BaiduException baiduException = new BaiduException();
            baiduException.setGmtCreate(new Date());
            baiduException.setExceptionMsg(ex.getMessage());
            baiduException.setOriginLatitude(String.valueOf(mapOrgrin.get("lat")));
            baiduException.setOriginLongitude(String.valueOf(mapOrgrin.get("lng")));
            baiduException.setDestinationLatitude(String.valueOf(mapDestinations.get("lat")));
            baiduException.setDestinationLongitude(String.valueOf(mapDestinations.get("lng")));
            iBaiduExceptionService.insert(baiduException);
        }
        return distance;
    }

    /**
     * 获取两地之间默认驾车导航距离
     *
     * @param origins
     * @param destinations
     * @return
     * @throws BaseException
     */
    public static double getDistance(String origins, String destinations) throws BaseException {
        double distance = getDistance(origins, destinations, "13");
        return distance;
    }

    /**
     * 获取两地之间默认驾车导航距离
     *
     * @param mapOrgrin       起始点坐标的map lat 纬度 lng 经度
     * @param mapDestinations 终点坐标的map lat 纬度 lng 经度
     * @return
     * @throws BaseException
     */
    public static double getDistance(Map<String, Double> mapOrgrin, Map<String, Double> mapDestinations) throws BaseException {
        double distance = getDistance(mapOrgrin, mapDestinations, "13");
        return distance;
    }

    /**
     * 获取两地之间默认驾车导航距离
     * @param mapOrgrin 经纬度方式起点
     * @param destinations 地址文本方式终点
     * @return double
     * @throws BaseException
     */
    public static double getDistance(Map<String, Double> mapOrgrin, String destinations) throws BaseException {
        Map<String,Double> mapDest = BaiDuMapGeocodeUtil.addressToGPS(destinations);
        double distance = getDistance(mapOrgrin, mapDest, "13");
        return distance;
    }
}